package com.smbms.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName MybatisUtil
 * @Description Mybatis工具类
 * @Author 12994
 * @Date 2024/10/17 12:30
 * @Version 1.0
 **/
public class MybatisUtil {
    private static final SqlSessionFactory ssf;

    // 静态代码块, 在创建对象之前(JVM加载期)只执行一次
    static {
        try {
            InputStream is = Resources.getResourceAsStream("./mybatis-config.xml");
            // 设置非默认环境
            ssf = new SqlSessionFactoryBuilder().build(is, "smbms");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得会话
     */
    public static SqlSession getSqlSession() {
        // 是否自动提交事务
        return ssf.openSession(true);
    }

    /**
     * 释放会话
     */
    public static void releaseSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    public static void main(String[] args) {
        // 测试
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        MybatisUtil.releaseSqlSession(sqlSession);
    }
}
